/*
 * CS_BLACKSMITH_UPSTONE_COMPLETE.cpp
 *
 *  Created on: 2013. 5. 28.
 *      Author: mega@gamevil.com
 */

#include "../../Command.h"
#include "../../User.h"
#include "../../NLogic/Item.h"
#include "../../NLogic/Bag.h"
#include "../../NLogic/VirtualCurrency.h"
#include "../../NResource/Static.h"

namespace ProjectZ { namespace NCommand {

void SendFailUpstoneComplete(User * pUser, int res)
{
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(res);
	*pAck << static_cast<uint8_t>(0);
	*pAck << static_cast<uint64_t>(0);
	pAck->MakePacket(CMD_SC_BLACKSMITH_UPSTONE_COMPLETE);
	pUser->Send(pAck);
}

void Command::CS_BLACKSMITH_UPSTONE_COMPLETE(User * pUser, ::Network::Packet * pPacket)
{
/*	ZNO_CS_BLACKSMITH_UPSTONE_COMPLETE  //0x2206
	{
		u64	upstone_seq;	// 강화 시퀀스
	}

	// 강화석 생성 즉시 완료 응답
	ZNO_SC_BLACKSMITH_UPSTONE_COMPLETE  //0x2207
	{
		s16	s16_ack;		// 결과
		u8	u8bag_type;
		u64	u64item_seq;		// 아이템 시컨스
	}*/

	PREPARE_PACKET;

	uint64_t upstoneSeq = 0;

	*pPacket >> upstoneSeq;

	NLogic::Bag * pBag = pUser->GetBag(BAG_TYPE_ACCESSORY);
	if (NULL == pBag)
	{
		PROCESSLOG("CS_BLACKSMITH_UPSTONE_COMPLETE : pBag is NULL!");
		return;
	}

	int remainSec	= 0;
	int needZen		= 0;
	int itemLevel	= 0;
	int itemQuality	= 0;
	int status		= 0;

	{
		::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
		clsAuto->SetQueryType(::Database::Command::S_PROCEDURE);
		
	//--------------------------------------------------------------------------------------------------------------------------
		// 제작 중이던 강화석 목록 data가 소멸되는 오류 수정, Changed by spencer(2014.06.19)

		// 강화석을 삭제하게 될 때, client 측에서 전달한 upstoneSeq 값만을 사용해서 DB 삭제를 수행한다.
		// 만약 client로부터 전달된 강화석 key값이 해당 유저 소유가 아니라면, 타인의 data를 삭제하게 되는 결과를 야기한다.

		// => 삭제 시에 소유주도 명확히 하여서 잘못될 수 있는 삭제 루틴을 보완한다.
		//--------------------------------------------------------------------------------------------------------------------------
		//clsAuto->MakeQuery("call sp_select_data_upstone_complete(%lld)", upstoneSeq);
		clsAuto->MakeQuery("call sp_select_data_upstone_complete_new(%d, %lld)", pUser->GetCharacterInfo().characterseq, upstoneSeq);

		if (false == ::Database::GETSESSION()->SyncExecute(pUser->GetUserInfo().shard_Item_db_type, clsAuto))
		{
			PROCESSLOG("CS_BLACKSMITH_UPSTONE_COMPLETE : false == ::Database::GETSESSION()->SyncExecute");
			return;
		}

		if (clsAuto->GetErrorIdx() != 0)
		{
			PROCESSLOG("CS_BLACKSMITH_UPSTONE_COMPLETE : clsAuto->GetErrorIdx() != 0");
			return;
		}

		while (clsAuto->Next())
		{
			clsAuto->GetRecord() >> itemQuality >> itemLevel >> remainSec >> needZen >> status;
		}
	}

	// 이미 완료된 경우
	if (1 == status)
	{
		DEBUGLOG("CS_BLACKSMITH_UPSTONE_COMPLETE : 1 == status");
		return;
	}

	// 강화석 데이터 생성
	NLogic::Item::Data clsData;

	clsData.quantity 	= 1;			// 수량
	clsData.tid 		= UPSTONE_TID;	// tid
	clsData.class_type	= -1;			// 장착 클래스 타입
	clsData.level		= itemLevel;	// 생성 될 강화석 레벨
	clsData.quality		= itemQuality;	// 생성 될 강화석 등급
	clsData.sub_type	= CLASS_ITEM_TABLE_ETC;
	clsData.bag_type 	= BAG_TYPE_ACCESSORY;

	NResource::BalanceData * pBalance = NResource::Static::InstancePtr()->GetBalance()->GetBalancePtr(pUser);
	if (NULL == pBalance)
	{
		DEBUGLOG("CS_BLACKSMITH_UPSTONE_COMPLETE : pBalance is NULL!");
		return;
	}

	bool bVCProcess = false;

	// 남은 시간이 3초 이내면 완료로 판단
	if (remainSec <= pBalance->GetValue(EM_UPSTONE_COMBINE_COMPLETE_ADMIT_SEC))
	{
		// do nothing
	}
	else
	{
		if (pUser->GetVirtualCurrency()->GetZen() < needZen)
		{
			SendFailUpstoneComplete(pUser, ACK_NOT_ENOUGH_ZEN);
			return;
		}

		bVCProcess = true;
	}

	// 강화석 데이터 저장
	bool bBagFull = false;
	NLogic::Item * pItem = pBag->AddItemWithData(clsData, bBagFull);
	if (NULL == pItem)
	{
		if (true == bBagFull)
		{
			SendFailUpstoneComplete(pUser, ACK_INVEN_BAG_FULL);
			return;
		}

		PROCESSLOG("CS_BLACKSMITH_UPSTONE_COMPLETE : pItem is NULL!!");
		return;
	}


	// 강화석 데이터 삭제, status를 1로 변경(list 획득 시, status가 0인 것만 select)
	{
		::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
		clsAuto->SetQueryType(::Database::Command::S_PROCEDURE);
		//clsAuto->MakeQuery("call sp_update_data_upstone_status_new(%lld)", upstoneSeq);
		clsAuto->MakeQuery("call sp_update_data_upstone_status_new(%d, %lld)", pUser->GetCharacterInfo().characterseq, upstoneSeq);

		if (false == ::Database::GETSESSION()->SyncExecute(pUser->GetUserInfo().shard_Item_db_type, clsAuto))
		{
			PROCESSLOG("CS_BLACKSMITH_UPSTONE_COMPLETE : false == ::Database::GETSESSION()->SyncExecute");
			return;
		}

		if (clsAuto->GetErrorIdx() != 0)
		{
			PROCESSLOG("CS_BLACKSMITH_UPSTONE_COMPLETE : clsAuto->GetErrorIdx() != 0");
			return;
		}
	}

	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(ACK_OK);
	*pAck << static_cast<uint8_t>(clsData.bag_type);
	*pAck << pItem->GetItemSeq();
	pAck->MakePacket(CMD_SC_BLACKSMITH_UPSTONE_COMPLETE);
	pUser->Send(pAck);

	// VC 처리
	if (true == bVCProcess)
	{
		NLogic::NFunction::VCProcess(pUser, EM_VCINDEX_UPSTONE_COMPLETE, needZen);
	}
}

} /*NCommand*/ } /*ProjectZ*/
